<?php
class COnline_message
{
	var $LAST_ERROR = "";

	function CheckFields($arFields, $ID = false)
	{
		if (!is_array($arFields))
			return false;

		if ($ID === false)
		{
			if (!isset($arFields["STREAM_ID"]))
				$this->LAST_ERROR .= "STREAM_ID not set"."<br>";
			if (!isset($arFields["OWNER_ID"]))
				$this->LAST_ERROR .= "OWNER_ID not set"."<br>";
			if (!isset($arFields["MESSAGE"]))
				$this->LAST_ERROR .= "MESSAGE not set"."<br>";
		}

		if (isset($arFields["STREAM_ID"]))
		{
			$arFields["STREAM_ID"] = intval($arFields["STREAM_ID"]);
			if  ($arFields["STREAM_ID"] > 0)
			{
				$ob_stream = new CConsultStream;
				$DBres = $ob_stream->GetByID ($arFields["STREAM_ID"]);
				if (!$DBres)
					$this->LAST_ERROR .= "STREAM_ID not found"."<br>";
			}
			else
				$this->LAST_ERROR .= "STREAM_ID contain incorrect value"."<br>";

		}

		if (isset($arFields["MESSAGE"]) && strlen(trim($arFields["MESSAGE"])) <= 0)
			$this->LAST_ERROR .= "MESSAGE field is empty"."<br>";

		if (isset($arFields["OWNER_ID"]))
		{
			$arFields["OWNER_ID"] = intval($arFields["OWNER_ID"]);
			if  ($arFields["OWNER_ID"] > 0)
			{
				$ob_stream = new CConsultUser;
				$DBres = $ob_stream->GetList (array(), array("ID" => $arFields["STREAM_ID"]));
				if (!$DBres)
					$this->LAST_ERROR .= "OWNER_ID not found"."<br>";
			}
			else
				$this->LAST_ERROR .= "OWNER_ID contain incorrect value"."<br>";

		}

		if (isset ($arFields["DATE_CREATE"]) && !CheckDateTime($arFields["DATE_CREATE"]))
			$this->LAST_ERROR .= "DATE_CREATE contain incorrect value"."<br>";

		if (isset ($arFields["DATE_READ"]) && !CheckDateTime($arFields["DATE_READ"]))
			$this->LAST_ERROR .= "DATE_READ contain incorrect value"."<br>";

		if(strlen($this->LAST_ERROR)>0)
			return false;
		return true;
	}
	function Update($ID, $arFields)
	{
		global $DB;
		$this->LAST_ERROR = ""; 
		$this->METHOD = "COnline_message::Update(".__LINE__.")";

		$ID = intval($ID);
		
		if(!$this->CheckFields($arFields, $ID))
		{
			return false;
		}
		else
		{
			unset ($arFields["DATE_CREATE"]);
			unset ($arFields["ID"]);
			
			/*foreach ($arFields as $key => $val);
			{
				if (strpos($key, 0, 1) == "=")
				{
					$arFields["~".$key] = $arFields["=".$key];
					unset($arFields["=".$key]);
				}
				
			}*/
			$strUpdate = $DB->PrepareUpdate("b_consult_messages", $arFields);
			$strSql = "UPDATE b_consult_messages SET ".$strUpdate." WHERE ID=".$ID;
			//echo "<pre>".$strSql."</pre>";
			$DBres = $DB->Query($strSql, false, "FILE: ".__FILE__."<br> LINE: ".__LINE__);

			if ($DBres) 
				return  true;
			
			return false;

		}
	}
	function Add($arFields)
	{

		global $DB;
		$this->LAST_ERROR = "";
		$this->METHOD = "COnline_message::Add(".__LINE__.")";

		if (!COnline_message::CheckFields($arFields))
			return false;

		$Stream_id = $arFields["STREAM_ID"];
		$strSql = "SELECT max(NUMBER) MAX_NUMBER FROM b_consult_messages WHERE STREAM_ID='$Stream_id'";

		$z = $DB->Query($strSql, false, $err_mess.__LINE__);
		$zr = $z->Fetch();
		$MAX_NUMBER = intval($zr['MAX_NUMBER']);

		$dbInsert = array(
			"STREAM_ID" =>	 $arFields["STREAM_ID"],
			"OWNER_ID" =>	 $arFields["OWNER_ID"],
			"MESSAGE" =>	 $arFields["MESSAGE"],
			"NUMBER" =>	 $MAX_NUMBER + 1,
			"~DATE_CREATE"	=> $DB->GetNowFunction(),
		);

		$arInsert = $DB->PrepareInsert("b_consult_messages", $dbInsert);
		$strSqlInsert =	"INSERT INTO b_consult_messages(".$arInsert[0].") ".
				"VALUES(".$arInsert[1].")";
		if ($DB->Query($strSqlInsert))
			return $DB->LastID();

		return false;
	}

	function GetMessagesForChat($stream_id, $last_id)
	{
		global $DB;
		$stream_id = intval ($stream_id);

		$last_id = intval ($last_id);
		
		$sqlLastID = " AND CM.ID > ".$last_id." ";

		$strSql = "SELECT CM.ID, CM.STREAM_ID, CM.OWNER_ID, IF (CU.ENTITY_TYPE = 'U', CU.ENTITY_ID, NULL) as REAL_USER_ID, CU.NAME as USER_NAME, CM.MESSAGE, CM.NUMBER, 
				".$DB->DateToCharFunction("CM.DATE_CREATE", "FULL")." as DATE_CREATE
			FROM b_consult_messages CM 
			LEFT JOIN b_consult_user as CU on CM.OWNER_ID = CU.ID
			WHERE 
				1 = 1 AND CM.STREAM_ID = ".$stream_id.$sqlLastID."
			ORDER BY DATE_CREATE ASC";
			//echo $strSql;
		$db_res = $DB->Query($strSql, false, "File: ".__FILE__."<br>Line: ".__LINE__);
		if ($db_res)
		{
			$arRes = array();
			while ($ar = $db_res->Fetch())
				$arRes[] = $ar;
			return $arRes;
		}
		return false;

	}

	function GetList($arOrder = Array("ID"=>"ASC"), $arFilter = array())
	{
		global $DB;
		$arSqlSearch = array();
		$arSqlOrder = array();
		$strSqlSearch = "";
		$strSqlOrder = "";
		$arFilter = (is_array($arFilter) ? $arFilter : array());
		//$arAddParams = (is_array($arAddParams) ? $arAddParams : array());
		
		foreach ($arFilter as $key => $val)
		{
			$key_res = CConsultUtil::GetFilterOperation($key);
			$key = strtoupper($key_res["FIELD"]);
			$strNegative = $key_res["NEGATIVE"];
			$strOperation = $key_res["OPERATION"];
			
			switch ($key)
			{
				case "ID":
				case "STREAM_ID":
				case "OWNER_ID":
				case "NUMBER":
					if (($strOperation!="IN") && (intVal($val) > 0))
							$arSqlSearch[] = ($strNegative=="Y"?" CM.".$key." IS NULL OR NOT ":"")."(CM.".$key." ".$strOperation." ".intVal($val)." )";
					elseif (($strOperation =="IN") && ((is_array($val) && count($val)>0 && (array_sum($val) > 0)) || (strlen($val) > 0) ))
					{
						if (is_array($val))
						{
							$val_int = array();
							foreach ($val as $v)
								$val_int[] = intVal($v);
							$val = implode(", ", $val_int);
						}
						$arSqlSearch[] = ($strNegative=="Y"?" NOT ":"")."(CM.".$key." IN (".$DB->ForSql($val).") )";
					}
					else
						$arSqlSearch[] = ($strNegative=="Y"?"NOT":"")."(CM.".$key." IS NULL OR CM.".$key."<=0)";
					break;
				case "MESSAGE":
					if (strlen($val)<=0)
						$arSqlSearch[] = ($strNegative=="Y"?"NOT":"")."(CM.".$key." IS NULL OR LENGTH(CM.".$key.")<=0)";
					else
						$arSqlSearch[] = ($strNegative=="Y"?" CM.".$key." IS NULL OR NOT ":"")."(CM.".$key." ".$strOperation." '".$DB->ForSql($val)."' )";
					break;
				case "DATE_CREATE":
					if (strlen($val)<=0)
						$arSqlSearch[] = ($strNegative=="Y"?"NOT":"")."(CM.".$key." IS NULL OR LENGTH(CM.".$key.")<=0)";
					else
						$arSqlSearch[] = ($strNegative=="Y"?" CM.".$key." IS NULL OR NOT ":"")."(CM.".$key." ".$strOperation." ".$DB->CharToDateFunction($DB->ForSql($val), "FULL")." )";
					break;
			}
		}
		if (count($arSqlSearch) > 0)
			$strSqlSearch = " AND (".implode(") AND (", $arSqlSearch).") ";
		
		foreach ($arOrder as $by=>$order)
		{
		
			$by = strtoupper($by); $order = strtoupper($order);
			if ($order!="ASC") $order = "DESC";
			if ($by == "STREAM_ID") $arSqlOrder[] = " CM.STREAM_ID ".$order." ";
			elseif ($by == "OWNER_ID") $arSqlOrder[] = " CM.OWNER_ID ".$order." ";
			elseif ($by == "NUMBER") $arSqlOrder[] = " CM.NUMBER ".$order." ";
			elseif ($by == "DATE_CREATE") $arSqlOrder[] = " CM.DATE_CREATE ".$order." ";
			else
			{
				$arSqlOrder[] = " CM.ID ".$order." ";
				$by = "ID";
			}
		}
		$arSqlOrder = array_unique($arSqlOrder);
		DelDuplicateSort($arSqlOrder);
		if(count($arSqlOrder) > 0)
			$strSqlOrder = " ORDER BY ".implode(", ", $arSqlOrder);
			
		$strSql =
			"SELECT CM.ID, CM.STREAM_ID, CM.OWNER_ID, CU.ENTITY_ID as REAL_USER_ID, CU.NAME as USER_NAME, CM.MESSAGE, CM.NUMBER, 
				".$DB->DateToCharFunction("CM.DATE_CREATE", "FULL")." as DATE_CREATE,  
				".$DB->DateToCharFunction("CM.DATE_READ", "FULL")." as DATE_READ 
			FROM b_consult_messages CM
			LEFT JOIN b_consult_user as CU on CM.OWNER_ID = CU.ID AND CU.ENTITY_TYPE = 'U'
			WHERE 1 = 1
			".$strSqlSearch."
			".$strSqlOrder;
	
		$db_res = $DB->Query($strSql, false, "File: ".__FILE__."<br>Line: ".__LINE__);
		//echo $strSql;
		return $db_res;		
	}
}
?>